package com.lottery.common.advice;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lottery.pojo.ResponseEntity;

/**
 * 异常拦截器
 * 
 * @author Chaohui.Guo
 *
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

  @ExceptionHandler(value = IllegalArgumentException.class)
  @ResponseBody
  public ResponseEntity argumentErrorHandler(HttpServletRequest request, IllegalArgumentException e) {
    return handleException(e.getMessage(), e, HttpStatus.BAD_REQUEST, request);

  }

  @ExceptionHandler(value = RuntimeException.class)
  @ResponseBody
  public ResponseEntity runtimeErrorHandler(HttpServletRequest request, RuntimeException e) {
    return handleException(e.getMessage(), e, HttpStatus.BAD_REQUEST, request);

  }

  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public ResponseEntity defaultErrorHandler(HttpServletRequest request, Exception e) {
    return handleException("服务器开小差，请稍后再试！", e, HttpStatus.BAD_REQUEST, request);

  }

  private ResponseEntity handleException(String showMessage, Exception e, HttpStatus status,
      HttpServletRequest request) {
    String xRequestedWith = request.getHeader("x-requested-with");
    System.err.println((StringUtils.isEmpty(xRequestedWith) ? "" : "Ajax ") + "Request Error : " + showMessage);
    if (xRequestedWith == null) { // 获取不到指定的请求头，则为普通请求
      throw new RuntimeException();
    } else {
      return new ResponseEntity(status.value(), e.getMessage(), null);
    }
  }

}
